<template>
  <div class="department-container">
    <div class="app-container">
      <page-tool>
        <template #left>
          <span>文字区域</span>
        </template>
        <template #right>
          <el-button type="danger" @click="$router.push('/employees/import')"> Excel导入 </el-button>
          <el-button type="warning" @click="exportExcel"> Excel导出 </el-button>
          <el-button type="primary" @click="hAdd()"> 新增 </el-button>
        </template>
      </page-tool>
      <el-card style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column sortable prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ FormData(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="goDetail(scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 15, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
      <el-form ref="addForm" :model="addForm" label-width="100px" :rules="validForm">
        <el-form-item prop="username" label="姓名">
          <el-input v-model="addForm.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="addForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop="timeOfEntry" label="入职时间">
          <el-date-picker
            v-model="addForm.timeOfEntry"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item prop="formOfEmployment" label="聘用形式">
          <el-select v-model="addForm.formOfEmployment" placeholder="请选择">
            <el-option v-for="ele in EmploymentList" :key="ele.id" :value="ele.id" :label="ele.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="workNumber" label="工号">
          <el-input v-model="addForm.workNumber" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item prop="departmentName" label="部门">
          <el-input v-model="addForm.departmentName" placeholder="请输入" @click.native="visible = !visible" />
          <el-popover
            v-model="visible"
            placement="top-start"
            width="200"
            trigger="manual"
          >
            <el-tree default-expand-all :data="treeList" :props="{label: 'name'}" @node-click="handleNodeClick" />
          </el-popover>

        </el-form-item>
        <el-form-item label="转正时间">
          <el-date-picker
            v-model="addForm.correctionTime"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { TYPE_MAP } from '@/constant/map'
import { getTree } from '@/utils/getTree'
import { getEmployeesList, delEmployeesAPI, addEmployeeAPI } from '@/api/employees'
import { getDepartments } from '@/api/departments'
export default {
  data() {
    return {
      visible: false,
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false,
      addForm: {
        username: 'aaaa',
        mobile: '13200000011',
        workNumber: '22222',
        departmentName: '总裁办',
        formOfEmployment: '1',
        correctionTime: '',
        timeOfEntry: ''
      },
      validForm: {
        username: [
          { required: true, message: '请输入必填项', trigger: 'blur' },
          { min: 1, max: 4, message: '用户姓名为1-4位', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入必填项', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ]
      },
      EmploymentList: Object.keys(TYPE_MAP).map(ele => {
        return { id: ele, value: TYPE_MAP[ele] }
      }),
      treeList: []
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 测试
    testFn(a) {
      console.log(a)
    },
    // 点击查看
    goDetail(id) {
      this.$router.push('/employees/detail?id=' + id)
    },
    // 关闭dialog时的回调
    hClose() {
      this.$refs.addForm.resetFields()
    },
    // 新增员工
    async addEmployee() {
      try {
        await addEmployeeAPI(this.addForm)
        this.showDialog = false
        this.$message.success('新增成功')
        this.page = Math.ceil((++this.total) / this.size)
        this.getEmployees()
      } catch (err) {
        console.log('', err)
      }
    },
    // 点击tree
    handleNodeClick(data) {
      console.log(data)
      this.addForm.departmentName = data.name
      this.visible = false
    },
    // 点击新增按钮
    hAdd() {
      this.showDialog = true
      this.initDepartments()
    },
    // 部门数据渲染
    async initDepartments() {
      try {
        const res = await getDepartments()
        // 保存数据
        res.data.depts.shift()
        this.treeList = getTree(res.data.depts)
      } catch (err) {
        console.log('', err)
      }
    },
    // 表单提交按钮
    hSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return
        this.addEmployee()
      })
    },
    // 删除
    async delEmployees(id) {
      if (this.list.length === 1) (this.page > 1) && this.page--
      try {
        await delEmployeesAPI(id)
        // 保存数据
        this.getEmployees()
        this.$message.success('删除成功')
      } catch (err) {
        console.log('', err)
      }
    },
    // 点击了删除
    hDel(id) {
      this.$confirm('确认删除？', '系统提示').then(() => {
        this.delEmployees(id)
      }).catch(() => {
      })
    },
    // 格式化数据
    FormData(type) {
      return TYPE_MAP[type]
    },
    async getEmployees() {
      try {
        const res = await getEmployeesList({
          page: this.page,
          size: this.size
        })
        // 保存数据
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log('', err)
      }
    },
    handleSizeChange(val) {
      this.size = val
      this.page = 1
      this.getEmployees()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployees()
    },
    // 用户点击了导出
    exportExcel() {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 采用按需引入的方式，需要用到导出功能时，插件才会被引入到应用里
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: Object.keys(this.list[0]).map(ele => map[ele]), // 表头 必填
          data: this.list.map(ele => {
            ele.formOfEmployment = TYPE_MAP[ele.formOfEmployment]
            return Object.values(ele)
          }), // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }

  }
}
</script>
